/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: TelnetChildHandler
 * Author:   zengjian
 * Date:     2018/9/20 21:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package netty.telnet;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.Date;

/**
 * 〈〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/20 21:02
 */
public class TelnetChildHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new StringDecoder());
        ch.pipeline().addLast(new StringEncoder());
        ch.pipeline().addLast(new SimpleChannelInboundHandler() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                System.out.println("TelentServer接收到请求:\n" + msg);
                final ChannelFuture future1 = ctx.writeAndFlush("服务器返回消息" + new Date().toString());
                future1.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
                    @Override
                    public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                        if (future.isSuccess()) {
                            System.out.println("消息返回成功");
                        }
                    }
                });
            }
        });
    }
}